﻿using Corina.Common;
using Corina.Enumerations;
using Corina.Infrastructure;
using Corina.Win.Interface;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Corina.Commands;
using System.Text.RegularExpressions;
using System.Net;

namespace Corina.Addins.Spyrs
{
    [Export(typeof(IView))]
    public class SpyrsViewmodel : BaseClass, IView
    {
        WebClient client;

        public SpyrsViewmodel() {
            Title = "马刺战绩";
            UriString = "SpyrsView";
            UriType = Enumerations.UriType.InApp;
            Icon = "ICON_MEMORY_CARD";

            client = new WebClient();
            client.DownloadStringCompleted += DownloadStringCompleted;
        }

        private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                HtmlContent = System.Web.HttpUtility.HtmlDecode(e.Result);
                Resolve();
            }
        }

        #region Fields
        private int _pageIndex = 0;
        private string _title;
        private string _uriString;
        private UriType _uriType = UriType.OutApp;
        private string _icon;
        private int _index = 0;
        #endregion

        #region Properties
        public int PageIndex
        {
            get { return _pageIndex; }
            set
            {
                _pageIndex = value;
                RaisePropertyChanged(() => PageIndex);
            }
        }

        public string Icon
        {
            get { return _icon; }
            set
            {
                _icon = value;
                RaisePropertyChanged(() => Icon);
            }
        }

        public string Title
        {
            get { return _title; }
            set
            {
                _title = value;
                RaisePropertyChanged(() => Title);
            }
        }

        public string UriString
        {
            get { return _uriString; }
            set
            {
                _uriString = value;
                RaisePropertyChanged(() => UriString);
                RaisePropertyChanged(() => FullUrl);
            }
        }

        public UriType UriType
        {
            get { return _uriType; }
            set
            {
                _uriType = value;
                RaisePropertyChanged(() => UriType);
                RaisePropertyChanged(() => FullUrl);
            }
        }

        public string FullUrl
        {
            get
            {
                return UrlPrefix<SpyrsViewmodel>.Prefixs.FirstOrDefault(k => k.Key == UriType).Value + "Views/" + UriString + ".xaml";
            }
        }

        public int Index
        {
            get { return _index; }
            set
            {
                _index = value;
                RaisePropertyChanged(() => Index);
            }
        }
        #endregion

        private string _htmlContent = string.Empty;
        public string HtmlContent
        {
            get { return _htmlContent; }
            set {
                _htmlContent = value;
                RaisePropertyChanged(() => HtmlContent);
                RaisePropertyChanged(() => ResolveCommand);
            }
        }

        private string _weburl = string.Empty;
        public string Weburl
        {
            get { return _weburl; }
            set {
                _weburl = value;
                RaisePropertyChanged(() => Weburl);
                RaisePropertyChanged(() => ResolveCommand);
            }
        }

        private bool _showHtmlContent = true;
        public bool ShowHtmlContent
        {
            get { return _showHtmlContent; }
            set {
                _showHtmlContent = value;
                RaisePropertyChanged(() => ShowHtmlContent);
            }
        }

        private ObservableCollection<object> _itemsCollection;
        public ObservableCollection<object> ItemsCollection
        {
            get { return _itemsCollection; }
            set {
                _itemsCollection = value;
                RaisePropertyChanged(() => ItemsCollection);
            }
        }

        private void Resolve()
        {
            Task task = Task.Factory.StartNew(() =>
            {
                try
                {
                    string content = HtmlContent.Replace("\r", "").Replace("\n", "").Replace(" class=\"odd\"", "").Replace(" class=\"even\"", "");
                    IEnumerable<string> tr_items = Regex.Matches(content, "<tr>(.*?) </tr>").OfType<Match>().Select(t => t.Value);

                    var items = from t in tr_items.Where(i => !i.Contains("日"))
                                select new
                                {
                                    Opponent = Regex.Match(t, "--> (.*?) <!--").Value.Trim().Replace(" ", "").Replace("-->", "").Replace("<!--", ""),
                                    Result = Regex.Replace(Regex.Matches(t, "<td class=\"statsText\">(.*?)</td>").OfType<Match>().LastOrDefault().Value, "<td (.*?)\">", "").Replace("</td>", "").Replace(" ", "").Substring(0, 1),
                                    Point = Regex.Replace(Regex.Matches(t, "<td class=\"statsText\">(.*?)</td>").OfType<Match>().LastOrDefault().Value, "<td (.*?)\">", "").Replace("</td>", "").Replace(" ", "").Substring(1)
                                };

                    ItemsCollection = new ObservableCollection<object>(items.OrderBy(t => t.Opponent));

                    ShowHtmlContent = false;
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show(ex.Message);
                }
            });
        }

        public ICommand ResolveCommand
        {
            get {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return !string.IsNullOrEmpty(HtmlContent) || !string.IsNullOrEmpty(Weburl); },
                    ExecuteCallback = delegate {
                        if (!string.IsNullOrEmpty(Weburl))
                        {
                            client.DownloadStringAsync(new Uri(Weburl, UriKind.RelativeOrAbsolute));
                        }
                        else
                        {
                            Resolve();
                        }
                    }
                };
            }
        }

        public ICommand EditCommand
        {
            get
            {
                return new GenericCommand()
                {
                 
                    ExecuteCallback = delegate
                    {
                        ShowHtmlContent = true;
                    }
                };
            }
        }
    }
}
